<?php
/**
 * Class loader for runtime
 * @package pworks.mvc.util
 */
class ClassLoader
{
	/**
	 * @param string classFullName, full name for the class, e.g.: pworks.mvc.util.ClassLoader
	 * @param string src, php soruce file path, must be a relative path to include_path evironment variable, or a absolute path
	 * @return Object, instance of specific class.
	 */
	public static function getInstance($classFullName, $src=null)
	{
		$nameParts = explode(".",$classFullName);
		$className = end($nameParts);
		if($src != null){
			$classPath = $src;
		}else{
			$classPath = implode('/',$nameParts);
			$classPath = $classPath.".class.php";
		}

		if(class_exists($className,false)){
			$obj = new $className();
			return $obj;
		}else{
			if(include $classPath)
			{
				if(class_exists($className,false)){
					$obj = new $className();
					return $obj;
				}else{
					$e = new SystemException(SystemException::PHP_ERROR, "Class $className is not defined");
					throw $e;
				}
			}
			else
			{
				$includePath = get_include_path();
				$e = new SystemException(SystemException::PHP_ERROR, "Source File $classPath could not be found in: $includePath");
				throw $e;
			}
		}
	}
	
	public static function isClassExist($classFullName, $src=null){
		$nameParts = explode(".",$classFullName);
		$className = end($nameParts);
		if(class_exists($className,false)){
			return true;
		}
		
		if($src != null){
			$classPath = $src;
		}else{
			$classPath = implode('/',$nameParts);
			$classPath = $classPath.".class.php";
		}

		if(include $classPath)
		{
			if(class_exists($className,false)){
				return true;
			}else{
				$e = new SystemException(SystemException::PHP_ERROR, "Class $className is not defined");
				throw $e;
			}
		}
		else
		{
			$includePath = get_include_path();
			$e = new SystemException(SystemException::PHP_ERROR, "Source File $classPath could not be found in: $includePath");
			throw $e;
		}
	}
}
